package com.zd.springcloud.consumer.tccaction.impl;

import com.zd.springcloud.consumer.mapper.AccountMapper;
import com.zd.springcloud.consumer.tccaction.AccountAction;
import com.zd.springcloud.domain.Account;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AccountActionImpl implements AccountAction{

    @Autowired(required = false)
    AccountMapper accountMapper;

    @Override
    public void reduceMoney(BusinessActionContext businessActionContext, double money, long accountId) {

        String xid = businessActionContext.getXid();
        //解决幂等问题
        if (accountMapper.existsTryLog(xid) > 0){
            return;
        }

        //解决悬挂问题 没有执行过try 或者 commit就执行 try
        if(accountMapper.existsCommitLog(xid)>0 || accountMapper.existsRollbackLog(xid)>0){
            return;
        }


        //判断钱是否够
        Account account = accountMapper.findAccoutById(accountId);

        if(account.getAccountMoney() < money){
            throw  new RuntimeException("您的账户余额不足 " + account.getAccountMoney());
        }

        accountMapper.reduceMoney(money,accountId);

        accountMapper.insertTryLog(xid);
    }

    @Override
    public void commit(BusinessActionContext businessActionContext) {
        double money = Double.parseDouble(businessActionContext.getActionContext("money").toString());
        Long accountId = Long.parseLong(businessActionContext.getActionContext("accountId").toString());

        String xid = businessActionContext.getXid();
        //解决幂等问题
        if (accountMapper.existsCommitLog(xid) > 0){
            return;
        }
        //解决空提交的问题，一般很少发生
        if(accountMapper.existsTryLog(xid)==0){
            return;
        }

        accountMapper.reduceCommit(money,accountId);

        accountMapper.insertCommitLog(xid);

    }

    @Override
    public void rollback(BusinessActionContext businessActionContext) {

        String xid = businessActionContext.getXid();

        //解决幂等问题
        if (accountMapper.existsRollbackLog(xid) > 0){
            return;
        }
        //解决空回滚的问题
        if(accountMapper.existsTryLog(xid)==0){
            return;
        }

        double money = Double.parseDouble(businessActionContext.getActionContext("money").toString());
        Long accountId = Long.parseLong(businessActionContext.getActionContext("accountId").toString());
        accountMapper.reduceRollback(money,accountId);


        //回滚后添加日志
        accountMapper.insertRollbackLog(xid);

    }
}
